import os
import win32com.client


def pwd_xlsx(old_filename, new_filename, pwd_str, pw_str='CAICT0817'):  # pw_str为打开密码, 若无 访问密码, 则设为 ''
    try:
        xcl = win32com.client.Dispatch("Excel.Application")
        wb = xcl.Workbooks.Open(old_filename, False, False, None, pw_str)
        xcl.DisplayAlerts = False  # 保存时可设置访问密码.
        print(new_filename)
        wb.SaveAs(new_filename, None, pwd_str, '')
        xcl.Quit()
    except:
        xcl.Quit()
        print(new_filename + '保存失败')


if __name__ == '__main__':
    path = 'D:/Documents/疫情数据/通管局数据/20210817/待下发/'
    savepath = 'D:/Documents/疫情数据/通管局数据/20210817/已下发/'
    files = os.listdir(path)
    for file in files:
        #print(file)
        old_filename = path + file
        new_filename = savepath + file
        pwd_str = 'dsj'  # 新密码自定义
        pwd_xlsx(old_filename, new_filename, pwd_str)
